<template>
    <div class="login">
        <img class="left" :src="bgLeft" alt="bgLeft">
        <img class="right" :src="bgRight" alt="bgRight">
        <div class="body">
            <h2>登录</h2>
            <el-form ref="FormRef" :model="loginForm" :rules="rules" size="large">
                <el-form-item prop="username">
                    <el-input v-model="loginForm.phone_number" placeholder="请输入账号" />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="loginForm.password" show-password placeholder="请输入密码" />
                </el-form-item>
                <el-form-item>
                    <el-button class="login-btn" type="primary" @click="submitForm(FormRef)">
                        登录
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
<script setup>
import bgLeft from "@/assets/img/bg-left.png"
import bgRight from "@/assets/img/bg-right.png"
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import http from "../api/build.js"
import router from '../router'

const token = localStorage.getItem('token')
if (token) router.replace({ name: 'home' })

// 表单
const loginForm = reactive({
    phone_number: '',
    password: ''
})

// 校验
const rules = reactive({
    phone_number: [
        { required: true, message: '账号必填', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '密码必填', trigger: 'blur' },
    ],
})

// 提交表单
const FormRef = ref()
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            http.login(loginForm).then((data) => {
                if (data.code == 0) {
                    localStorage.setItem('token', data.data.user_token)
                    router.push({ name: 'home' })
                } else {
                    ElMessage.error('账号或密码错误！')
                }
            })
        }
    })
}

</script>
<style scoped>
.login {
    min-width: 1040px;
    width: 100vw;
    height: 100vh;
    position: relative;
}

.left {
    position: absolute;
    left: 0;
    bottom: 0;
}

.right {
    position: absolute;
    right: 0;
    bottom: 0;
}

.body {
    box-sizing: border-box;
    position: absolute;
    top: 40%;
    left: 50%;
    width: 500px;
    padding: 60px;
    z-index: 1;
    transform: translate(-50%, -50%);
    box-shadow: 0px 20px 80px 0px rgba(0, 0, 0, 0.3);
    background-color: white;
    display: flex;
    flex-direction: column;
}

.body h2 {
    margin-top: 0;
    color: #40485b;
}

.login-btn {
    width: 100%;
}
</style>